<?php

namespace addons\xilujob\chatprograms\library;

class Chat
{
    /**
     * 当前表情包所有数组数据
     * @return array        数组
     */
    public function chat_memes()
    {
        $data = \app\common\model\xilujob\ChatEmoji::where('status', 'normal')->order('weigh desc,id desc')->select();
        $arr = [];
        foreach ($data as $key => $value) {
            $arr[] = [
                'name' => $value['name'],
                'image' => cdnurl($value['image'],true),
            ];
        }
        return $arr;
    }
    /**
     * 系统消息的未读个数
     * @return array        数组
     */
    public function init_data($user_id)
    {
        $xiluuser = \app\common\model\xilujob\XilujobUser::get(['user_id'=>$user_id]);
        $myGroupId = $xiluuser->group_id;
        $num = \app\common\model\xilujob\Chat::where("to_group_id",$myGroupId)->where('to_uid', $user_id)->where('isread', 0)->count();
        $data['unread_num'] = $num;
        return $data;
    }
    /**
     * 获取当前通知信息数量 message: {type:getmessagecount,84fec134257974bdcccbf70050e43fa2}
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function getmessagecount($user_id,$message_data)
    {
        $returnData = [
            'code' => 1,
            'type' => 'message_count',
            'msg' => '',
            'data' => self::init_data($user_id), //接收数据
        ];
        return $returnData;
    }
    /**
     * 发送消息
     * @param int          $send_user_id  发送人id
     * @param array        $message_data  发送数据{type:say,receive_user_id:xx, content:xx,chat_type:1,session_id:1,see_type:0,84fec134257974bdcccbf70050e43fa2}
     */
    public function say($send_user_id, $message_data)
    {
        $returnData = ['code' => 0, 'type' => 'say', 'msg' => '发送失败，请稍后再试', 'data' => null];

        $receive_user_id = $message_data['receive_user_id'] ?? '';

        // 接收人id和产品id必须同时存在
        if (!$receive_user_id) {
            $returnData['msg'] = '参数错误';
            goto ret;
        }
        if ($receive_user_id == $send_user_id) {
            $returnData['msg'] = '自己不能和自己聊天';
            goto ret;
        }
        // 发送内容和类型必传
        if (empty($message_data['content']) || empty($message_data['chat_type'])) {
            $returnData['msg'] = '参数错误:发送内容和类型必传';
            goto ret;
        }
        #1.获取会话
        $session_data = \app\common\model\xilujob\ChatSession::checkSession($send_user_id,$receive_user_id);
        //可见状态:0=正常,1=自动打招呼(发送人不可见),2=发送人被拉黑(接收人不可见),3=接收人被拉黑(发送人不可见),4=相互拉黑(两方都不可见)
        $chatModel = new \app\common\model\xilujob\Chat;
        $see_type = $message_data['see_type'] ?? 0;
        if($message_data['chat_type'] == 3){
            //职位
            if($chatModel->where('session_id',$session_data['id'])->where('job_id',$message_data['content'])->find()){
                $returnData['code'] = 2;
                $returnData['msg'] = '错误信息:职位咨询已存在';
                goto ret;
            }
            $job = \app\common\model\xilujob\Job::with([
                'user'=>function($query){$query->withField('id,avatar,nickname');},
                'city'=>function($query){$query->withField('id,name');},
                'district'=>function($query){$query->withField('id,name');},
                'work_experience'=>function($query){$query->withField('id,name');},
                'education_level'=>function($query){$query->withField('id,name');},
                'benefits'=>function($query){$query->withField('id,name');},
                'enterpriseinfo'=>function($query){$query->withField('id,company_name,environment_images,lng,lat,address,logo');}
            ])
                ->where('job.id',$message_data['content'])
                ->where('job.status',\app\common\model\xilujob\Job::STATUS_ENABLED)
                ->find();
            if(!$job) {
                $returnData['msg'] = '错误信息:无法查询到该职位信息';
                goto ret;
            }
            $message_data['content'] = [
                'id'            =>  $job['id'],
                'name'          =>  $job['job_name'],
                'salary'        =>  $job['salary_text'],
                'city'          =>  $job['city'] ? $job['city']['name'] : '',
                'district'      =>  $job['district'] ? $job['district']['name'] : '',
                'work_experience'=> $job['work_experience'] ? $job['work_experience']['name'] : '',
                'education_level'=> $job['education_level'] ? $job['education_level']['name'] : '',
                'benefits'      =>  $job['benefits'],
                'company_id'    =>  $job['publisher_id'],
                'company_name'  =>  $job['enterpriseinfo'] ? $job['enterpriseinfo']['company_name']:'',
                'company_logo'  =>  $job['enterpriseinfo'] ? $job['enterpriseinfo']['logo']:'',
                'user_id'       =>  $job['user']?$job['user']['id']:0,
                'user_avatar'   =>  $job['user']?$job['user']['avatar']:'',
                'user_nickname' =>  $job['user']?$job['user']['nickname']:'',
            ];
        }
        else if ($message_data['chat_type'] == 4){
            #投递
            $apply = \app\common\model\xilujob\JobApply::with(['job'])->field("job_apply.id,job_id")->where('job_apply.id',$message_data['content'])->find();
            if (!$apply) {
                $returnData['msg'] = '参数错误:无法查询到该投递信息';
                goto ret;
            }
            $job = $apply->job;
            $message_data['content'] = [
                'id'            =>  $job['id'],
                'name'          =>  $job['job_name'],
                'salary'        =>  $job['salary_text'],
                'in_hurry'      =>  $job['in_hurry'],
                'city'          =>  $job['city'] ? $job['city']['name'] : '',
                'district'      =>  $job['district'] ? $job['district']['name'] : '',
                'work_experience'=> $job['work_experience'] ? $job['work_experience']['name'] : '',
                'education_level'=> $job['education_level'] ? $job['education_level']['name'] : '',
                'benefits'      =>  $job['benefits'],
                'company_id'    =>  $job['publisher_id'],
                'company_name'  =>  $job['enterpriseinfo'] ? $job['enterpriseinfo']['company_name']:'',
                'company_logo'  =>  $job['enterpriseinfo'] ? $job['enterpriseinfo']['logo']:'',
                'user_id'       =>  $job['user']?$job['user']['id']:0,
                'user_avatar'   =>  $job['user']?$job['user']['avatar']:'',
                'user_nickname' =>  $job['user']?$job['user']['nickname']:'',
                'apply_id'      =>  $apply['id'],
            ];
        }
        else if ($message_data['chat_type'] == 5){
            #人才
            $resume = \app\common\model\xilujob\Resume::getResume($message_data['content'],true);
            if (!$resume) {
                $returnData['msg'] = '参数错误:无法查询到该简历信息';
                goto ret;
            }else{
                $returnData['code'] = 2;
                $returnData['msg'] = '人才咨询';
                goto ret;
            }
        }
        else if ($message_data['chat_type'] == 6){
            #邀请面试
            $interview = \app\common\model\xilujob\JobInterview::get($message_data['content']);
            if (!$interview) {
                $returnData['msg'] = '参数错误:无法查询到该面试邀请信息';
                goto ret;
            }
            $job = $interview->job;
            $message_data['content'] = [
                'id'            =>  $interview->id,
                'resume_id'     =>  $interview->resume_id,
                'interview_time'=>  $interview->interview_time,
                'interview_address'=>  $interview->address,
                'interview_contact'=>  $interview->contact,
                'interview_contact_phone'=>  $interview->contact_phone,
                'interview_contact_email'=>  $interview->contact_email,
                'job_id'        =>  $job['id'],
                'name'          =>  $job['job_name'],
                'salary'        =>  $job['salary_text'],
                'in_hurry'      =>  $job['in_hurry'],
                'city'          =>  $job['city'] ? $job['city']['name'] : '',
                'district'      =>  $job['district'] ? $job['district']['name'] : '',
                'work_experience'=> $job['work_experience'] ? $job['work_experience']['name'] : '',
                'education_level'=> $job['education_level'] ? $job['education_level']['name'] : '',
                'benefits'      =>  $job['benefits'],
                'company_id'    =>  $job['publisher_id'],
                'company_name'  =>  $job['enterpriseinfo'] ? $job['enterpriseinfo']['company_name']:'',
                'company_logo'  =>  $job['enterpriseinfo'] ? $job['enterpriseinfo']['logo']:'',
                'user_id'       =>  $job['user']?$job['user']['id']:0,
                'user_avatar'   =>  $job['user']?$job['user']['avatar']:'',
                'user_nickname' =>  $job['user']?$job['user']['nickname']:'',
            ];
        }
        // 创建聊天数据
        $new_msg = [
            'session_id'        =>  $session_data['id'],
            'from_uid'          => $send_user_id,
            'from_group_id'     =>  $send_user_id == $session_data['send_user_id'] ? $session_data['send_group_id'] : $session_data['receive_group_id'],
            'to_uid'            => $receive_user_id,
            'to_group_id'  =>  $receive_user_id == $session_data['send_user_id'] ? $session_data['send_group_id'] : $session_data['receive_group_id'],
            'see_type'          => $see_type,
            'message'           => is_array($message_data['content'])?json_encode($message_data['content']):$message_data['content'],
            'type'              => $message_data['chat_type'], //类型:1=文字,2=图片,3=职位,4=投递
            'job_id'            => isset($job)?$job['id'] : 0,
            'apply_id'          => isset($jobApply)?$jobApply['id'] : 0,
            'interview_id'      => isset($interview)?$interview['id'] : 0,
        ];
        $res = $chatModel->save($new_msg);
        if (!$res) {
            $returnData['msg'] = '发送失败';
            goto ret;
        }
        $session_data->updatetime = time();
        $session_data->allowField(['updatetime'])->save();
        $new_msg_id = $chatModel->id;
        // 获取最新消息
        $data = $chatModel->field(['id', 'session_id', 'to_uid', 'from_uid', 'message', 'type', 'see_type', 'createtime',])->with(['senduser' => function ($que) {
            $que->withField('id,nickname,avatar,gender');
        }, 'receiveuser' => function ($que) {
            $que->withField('id,nickname,avatar,gender');
        }])->where('chat.id', $new_msg_id)->find();
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $data;
        ret:
        return $returnData;
    }
    /**
     * 会话列表
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_time:0,session_id:0}
     */
    public function sessionlist($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'session_list',
            'msg' => '参数错误',
            'data' => '', //接收数据
        ];
        // // 判断是否传页数过来
        if ((!isset($message_data['pagesize'])) || (!isset($message_data['page']))) {
            goto ret;
        }
        $where = [];
        $chatmsgModel = new \app\common\model\xilujob\Chat;
        $xiluuser = \app\common\model\xilujob\XilujobUser::get(['user_id'=>$user_id]);
        $myGroupId = $xiluuser->group_id;
        //$receiveGroupId = $xiluuser->group_id == '2'?1:2;

        // 会话的可见状态:0=正常,1=发送人被拉黑(接收人不可见),2=接收人被拉黑(发送人不可见),4=相互拉黑(两方都不可见)
        $data = \app\common\model\xilujob\ChatSession::field(['id', 'send_user_id', 'receive_user_id','resume_id','company_id', 'see_type','updatetime',])
            ->with([
                'senduser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                },
                'receiveuser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                },
                'newmsg'
            ])
            ->where(function ($query) use ($user_id,$myGroupId) {
                $query->where(function ($query) use($user_id,$myGroupId){
                    $query->where('send_group_id',$myGroupId)
                        ->where('send_user_id', $user_id)
                        ->where('see_type', 'in', [0, 1])
                        ->whereNull('senddeletetime');
                })->whereOr(function ($query) use ($user_id,$myGroupId) {
                    $query->where('receive_group_id',$myGroupId)
                        ->where('receive_user_id', $user_id)
                        ->where('see_type', 'in', [0, 2])
                        ->whereNull('receivedeletetime');
                });
            })
            ->order('chat_session.updatetime desc,chat_session.id desc')
            ->paginate($message_data['pagesize'], false, ['page' => $message_data['page']])
            ->each(function ($row) use($chatmsgModel,$user_id){
                $row->unread_num = $chatmsgModel->where('session_id',$row->id)->where('to_uid',$user_id)->where('isread',0)->where('see_type', 'in', [0, 1])->count(1);
            });
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $data;
        ret:
        return $returnData;
    }
    /**
     * 聊天记录
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{page:1,product_id:1,receive_user_id:0}
     */
    public function msglist($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'msg_list',
            'msg' => '参数错误',
            'data' => [
                'current_page' => 1,
                'data' => [],
                'last_page' => 0,
                'total' => 0,
            ], //接收数据
            'receiveuser' => null,
        ];
        $receive_user_id = $message_data['receive_user_id'] ?? '';
        $page = $message_data['page'] ?? '1';
        // 接收人id和会话id必须有一个
        if (!$receive_user_id) {
            goto ret;
        }
        // 判断是否有会话id
        $session_data = \app\common\model\xilujob\ChatSession::checkSession($user_id,$receive_user_id);
        // 可见状态:0=正常,1=发送人删除记录(发送人暂不可见),2=接收人删除记录(接收人不可见),3=发送人撤回消息(双方都不可见),4=双方都删除记录
        $data = \app\common\model\xilujob\Chat::field(['id', 'session_id', 'from_uid', 'to_uid', 'message', 'type', 'see_type', 'createtime',])
            ->with(['senduser' => function ($que) {
            $que->withField('id,nickname,avatar,gender');
        }, 'receiveuser' => function ($que) {
            $que->withField('id,nickname,avatar,gender');
        }])
            ->where('session_id',$session_data['id'])
            ->order('chat.id desc')
            ->paginate(20, false, ['page' => $page]);

        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $data;
        // 获取接收人数据
        $returnData['receiveuser'] = \app\common\model\User::field('id,nickname,avatar,gender')->find($receive_user_id);
        ret:
        return $returnData;
    }
    /**
     * 设为已读
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_id:1,receive_user_id:0}
     */
    public function setread($user_id, $message_data){
        $returnData = ['code' => 0, 'type' => 'set_read', 'msg' => '参数错误', 'data' => null];
        // 接收人id和会话id必须有一个
        $receive_user_id = $message_data['receive_user_id'] ?? '';
        if (!$receive_user_id) {
            goto ret;
        }
        // 查询会话
        $session_data = \app\common\model\xilujob\ChatSession::checkSession($user_id,$receive_user_id);
        // 如果没有会话，直接返回空数组
        if (!$session_data) {
            goto ret;
        }

        \app\common\model\xilujob\Chat::where('session_id', $session_data['id'])->where('to_uid', $user_id)->where('isread', 0)->update(['isread' => 1]);

        $returnData['code'] = 1;
        $returnData['msg'] = $session_data;
        ret:
        return $returnData;
    }

    /**
     * 删除消息
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_id:1}
     */
    public function delchat($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'del_chat',
            'msg' => '参数错误',
            'data' => [], //接收数据
        ];
        $chat_id = $message_data['content'] ?? '';
        $chat = \app\common\model\xilujob\Chat::where('id',$chat_id)->find();
        if((time()-$chat['createtime'])>120){
            $returnData['msg'] = "超过2分钟的不可撤销";
            goto ret;
        }
        if(!$chat){
            $returnData['msg'] = "未找到聊天记录";
            goto ret;
        }
        $chat->delete();
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $chat;
        ret:
        return $returnData;
    }
    /**
     * 删除会话
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_id:1}
     */
    public function delsession($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'del_session',
            'msg' => '参数错误',
            'data' => [], //接收数据
        ];
        $receive_user_id = $message_data['receive_user_id'] ?? '';
        // 判断是否存在该会话
        $session_data = \app\common\model\xilujob\ChatSession::checkSession($user_id,$receive_user_id);
        if ($session_data['send_user_id'] == $user_id) {
            $session_data->save(['senddeletetime' => time()]);
        } else {
            $session_data->save(['receivedeletetime' => time()]);
        }
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = [];
        ret:
        return $returnData;
    }

}
